package com.sniper.springmvc.action;

import com.sniper.springmvc.utils.Verify;
import com.sniper.springmvc.utils.VerifyCode;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

/**
 * 提供图片验证码
 *
 * @author laolang
 */
@SessionAttributes("sessionVerifyName")
@Controller
public class VerifyAction {

    public static final String VALIDATE_CODE;

    static {
        VALIDATE_CODE = "sessionVerifyName";
    }

    public VerifyAction() {

    }


    @ResponseBody
    @RequestMapping("verify")
    public ResponseEntity<byte[]> verify(HttpServletResponse response, HttpServletRequest request)
            throws Exception {
        // 如果开启Hard模式，可以不区分大小写
        String securityCode = VerifyCode.getSecurityCode(5,
                VerifyCode.SecurityCodeLevel.Hard, false).toLowerCase();
        // 获取默认难度和长度的验证码
        // String securityCode = VerifyCode.getSecurityCode();
        // 图片流
        ServletOutputStream outputStream = response.getOutputStream();
        BufferedImage bufferedImage = Verify.createImage(securityCode);
        ImageIO.write(bufferedImage, "jpeg", outputStream);
        // 放入session中
        request.getSession().setAttribute(VALIDATE_CODE, securityCode);
        byte[] body = new byte[response.getBufferSize()];
        outputStream.write(body);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "image/jpeg");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        HttpStatus httpState = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<>(body, headers,
                httpState);
        return entity;
    }


    @RequestMapping("sniper")
    @ResponseBody
    public String sniper() {

        return "sniper";
    }

}